/*
 * @Author: wangyongcun
 * @Date: 2023-09-06 10:50:08
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-06-12 22:37:24
 * @Description: 项目管理
 */
class Project {
  constructor() {
    this.projectDic = {};
    this.queryProjectDic();
  }
  /**
   * @description: 添加项目信息
   * @param {*} ctx
   * @return {*}
   */
  async addProject(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["name"], ctx);
      if (isEmpty) return;
      // 查询数据是否已存在
      // 添加到数据库
      let rowBody = ctx.request.body;
      let rowBodyKeys = Object.keys(rowBody);
      let sqlParams = `id='${uuidv4()}',`;
      rowBodyKeys.forEach((x, i) => {
        if (Array.isArray(rowBody[x])) {
          rowBody[x] = JSON.stringify(rowBody[x]);
        }
        sqlParams += `${x}='${rowBody[x]}'${
          i == rowBodyKeys.length - 1 ? "" : ","
        }`;
      });
      let sql = `INSERT INTO project SET ${sqlParams}`;
      let { status } = await db(sql);
      if (status != 200) throw "添加项目失败";
      // 返回结果
      ctx.body = resUtil.success("添加成功");
    } catch (err) {
      log.error(`Project-addProject-登录失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 更新项目信息
   * @param {*} ctx
   * @return {*}
   */
  async updateProject(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 查询数据是否已存在
      // 添加到数据库
      let rowBody = ctx.request.body;
      let rowBodyKeys = Object.keys(rowBody);
      let sqlParams = "";
      rowBodyKeys.forEach((x, i) => {
        if (Array.isArray(rowBody[x])) {
          rowBody[x] = JSON.stringify(rowBody[x]);
        }
        sqlParams += `${x}='${rowBody[x]}'${
          i == rowBodyKeys.length - 1 ? "" : ","
        }`;
      });
      let sql = `UPDATE project SET ${sqlParams} WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.affectedRows == 0) throw "更新项目失败";
      // 返回结果
      ctx.body = resUtil.success("更新成功");
    } catch (err) {
      log.error(`Project-updateProject-更新失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 删除项目
   * @param {*} ctx
   * @return {*}
   */
  async deleteProject(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 添加到数据库
      let rowBody = ctx.request.body;
      let sql = `DELETE FROM project WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.affectedRows == 0) throw "未找到该项目";
      // 返回结果
      ctx.body = resUtil.success("删除成功");
    } catch (err) {
      log.error(`Project-deleteProject-删除失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 查询项目信息
   * @param {*} ctx
   * @return {*}
   */
  async queryProject(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 添加到数据库
      let rowBody = ctx.request.body;
      let sql = `SELECT * FROM project WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.length == 0) throw "未找到该项目";
      // 返回结果
      ctx.body = resUtil.success({ Content: results[0] });
    } catch (err) {
      log.error(`Project-queryProject-查询失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 查询列表
   * @param {*} ctx
   * @return {*}
   */
  async queryProjectList(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["pageNum", "pageSize"], ctx);
      if (isEmpty) return;
      let { pageNum, pageSize, keyword, userId } = ctx.request.body;
      let whereSql = "";
      if (keyword) {
        whereSql += keyword ? `WHERE name LIKE '%${keyword}%'` : "";
      }
      if (userId) {
        whereSql += `${
          whereSql ? " AND " : "WHERE "
        }  (followPerson LIKE '%${userId}%' OR responPerson='${userId}')`;
      }
      console.log(whereSql, "whereSql");
      // 查询总条数
      let Count = 0;
      let countSql = `SELECT COUNT(1) FROM project ${whereSql}`;
      let { status: countStatus, results: countRes } = await db(countSql);
      if (countStatus != 200) throw "查询总条数失败";
      Count = countRes[0]["COUNT(1)"];
      // 查询列表数据
      let listSql = `SELECT * FROM project ${whereSql} ORDER BY updateTime DESC LIMIT ${pageSize} OFFSET ${
        pageSize * (pageNum - 1)
      }`;
      let { status: listStatus, results: listRes } = await db(listSql);
      if (listStatus != 200) throw "查询项目列表失败";
      // 返回结果
      ctx.body = resUtil.success({ Content: listRes, Count });
    } catch (err) {
      log.error(`Project-queryProject-查询失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }

  /**
   * @description: 查询项目状态
   * @param {*} ctx
   * @return {*}
   */
  async queryProjectDic(ctx) {
    try {
      // 查询列表数据
      let listSql = `SELECT * FROM project_dic`;
      let { status: listStatus, results: listRes } = await db(listSql);
      if (listStatus != 200) throw "查询政策类型失败";
      // 返回结果
      this.projectDic = listRes;
      if (ctx) {
        ctx.body = resUtil.success({ Content: this.projectDic });
      }
    } catch (err) {
      log.error(`Policy-queryProjectDic-查询失败：${err}`);
      if (ctx) {
        ctx.body = resUtil.error(err);
      }
    }
  }
  /**
   * @description: 添加字典数据
   * @param {*} list
   * @return {*}
   */
  addDicInfo(list) {
    list.forEach((item) => {
      this.projectDic.forEach((dic) => {
        if (item[dic.type]) {
          item[dic.type + "Text"] = dic.value;
        }
      });
    });
  }
}

export default new Project();
